package com.luoran.bartalks.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * 判断office文件是什么版本的
 * 
 * @author M1nG
 * @date 2019年1月8日
 */
public class OfficeFileVersionPreJudge {

	/**
	 * 判断是否为老版本的excel
	 * 
	 * @Title: isExcel2003
	 * @param filePath *.xls
	 * @return boolean
	 * @author M1nG
	 * @date 2017-3-21 上午11:05:19
	 */
	public static boolean isExcel2003(String filePath) {
		return checkNull(filePath) && filePath.matches("^.+\\.(?i)(xls)$");
	}

	/**
	 * 判断是否为新版本的excel
	 * 
	 * @Title: isExcel2007
	 * @param filePath *.xlsx/*.xls
	 * @return boolean
	 * @author M1nG
	 * @date 2017-3-21 上午11:05:43
	 */
	public static boolean isExcel2007(String filePath) {
		return checkNull(filePath) && filePath.matches("^.+\\.(?i)(xlsx)$");
	}

	/**
	 * 根据excel的版本自动选择Workbook
	 * 
	 * @Title: selectWorkbook
	 * @param filePath   *.xlsx/*.xls/null
	 * @param versionTag 2007/2003/null
	 * @return Workbook
	 * @author M1nG
	 * @date 2017-3-21 上午11:05:43
	 */
	public static Workbook selectWorkbook(String filePath, String versionTag) {
		Workbook book = null;
		if (versionTag != null && !"".equals(versionTag)) {
			if ("2007".equals(versionTag)) {
				book = new XSSFWorkbook();
			} else if ("2003".equals(versionTag)) {
				book = new HSSFWorkbook();
			} else {
				book = new HSSFWorkbook();
			}
		} else {
			if (isExcel2007(filePath)) {
				book = new XSSFWorkbook();
			} else if (isExcel2003(filePath)) {
				book = new HSSFWorkbook();
			} else {
				book = new HSSFWorkbook();
			}
		}
		return book;
	}

	public static boolean checkNull(String filePath) {
		if (filePath == null || "".equals(filePath)) {
			return false;
		} else {
			return true;
		}

	}

}
